#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->widget->hide();
    ui->tableWidget->setColumnCount(3); //3列
    ui->tableWidget->setHorizontalHeaderLabels(QStringList()<<"书号"<<"书名"<<"数量");
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);

    database = QSqlDatabase::addDatabase("QSQLITE");

    database.setDatabaseName("/1.db");

    database.open();

    QSqlQuery query =  QSqlQuery(database);
    bool flag = query.exec("create table if not exists booktable(bookid text not null unique,name text not null unique,num int not null);");
    if(flag)
    {
        ui->statusBar->showMessage("数据库打开成功");
    }else{
        ui->statusBar->showMessage("数据库打开失败");
    }

    getTableAllInfo();

}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{
    QString bookid = ui->lineEdit->text().trimmed();
    QString name = ui->lineEdit_2->text().trimmed();
    QString num = ui->lineEdit_3->text().trimmed();

    if(bookid.isEmpty() || name.isEmpty() || num.isEmpty())
    {
        ui->statusBar->showMessage("数据不能为空");

        return;
    }

    QSqlQuery query = QSqlQuery(database);

    query.prepare("INSERT INTO booktable VALUES (:bookid, :name, :num)");
    // 绑定参数值
    query.bindValue(":bookid", bookid);
    query.bindValue(":name", name);
    query.bindValue(":num", num);

    // 执行查询
    if (!query.exec()) {
        ui->statusBar->showMessage("增加失败:" + query.lastError().text());
    } else{
        ui->statusBar->showMessage("增加成功!");
        getTableAllInfo();
    }

}

void MainWindow::getTableAllInfo()
{
    QSqlQuery query = QSqlQuery(database);

    query.exec("select * from booktable;");

    ui->tableWidget->clearContents(); // 清空现有内容（保留表头）
    ui->tableWidget->setRowCount(0);  // 重置行数为0，避免残留空行

    int row = 0;
    while (query.next()) {
        ui->tableWidget->insertRow(row); // 插入新行
        // 书号（第0列）
        QTableWidgetItem* idItem = new QTableWidgetItem(query.value("bookid").toString());
        idItem->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); // 居中
        ui->tableWidget->setItem(row, 0, idItem);

        // 书名（第1列）
        QTableWidgetItem* nameItem = new QTableWidgetItem(query.value("name").toString());
        nameItem->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); // 居中
        ui->tableWidget->setItem(row, 1, nameItem);

        // 数量（第2列）
        QTableWidgetItem* numItem = new QTableWidgetItem(query.value("num").toString());
        numItem->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); // 居中
        ui->tableWidget->setItem(row, 2, numItem);
        row++;
    }
}

void MainWindow::on_pushButton_2_clicked()
{
    QString name = ui->lineEdit_2->text().trimmed();

    // 输入验证：检查是否为空
    if (name.isEmpty()) {
        ui->statusBar->showMessage("请输入要删除的书名");
        return;
    }

    QSqlQuery query(database);

    query.prepare("DELETE FROM booktable WHERE name = :name");
    query.bindValue(":name", name);

    if (!query.exec()) {
        ui->statusBar->showMessage("删除失败: " + query.lastError().text());
    } else {
        if (query.numRowsAffected() == 0) {
            ui->statusBar->showMessage("未找到该书名，删除失败");
        } else {
            ui->statusBar->showMessage("删除成功!");
            getTableAllInfo(); // 刷新显示
        }
    }

}

void MainWindow::on_pushButton_3_clicked()
{
    QString bookid = ui->lineEdit->text().trimmed();
    QString name = ui->lineEdit_2->text().trimmed();
    QString num = ui->lineEdit_3->text().trimmed();

    if(bookid.isEmpty() || name.isEmpty() || num.isEmpty())
    {
        ui->statusBar->showMessage("数据不能为空");

        return;
    }

    QSqlQuery query = QSqlQuery(database);

    query.prepare("update booktable set name=:name where bookid=:bookid and num=:num;");
    // 绑定参数值
    query.bindValue(":bookid", bookid);
    query.bindValue(":name", name);
    query.bindValue(":num", num);

    // 执行查询
    if (!query.exec()) {
        ui->statusBar->showMessage("修改失败:" + query.lastError().text());
    } else{
        ui->statusBar->showMessage("修改成功!");
        getTableAllInfo();
    }
}

void MainWindow::on_actionc_triggered()
{
    getTableAllInfo();
}

void MainWindow::on_pushButton_4_clicked()
{
    QString bookid = ui->lineEdit->text().trimmed();
    if (bookid.isEmpty())
    {
        ui->statusBar->showMessage("书号不能为空");
        return;
    }

    QSqlQuery query = QSqlQuery(database);

    query.prepare("select * from booktable where bookid=:bookid");
    // 绑定参数值
    query.bindValue(":bookid", bookid);

    query.exec();
    ui->tableWidget->clearContents(); // 清空现有内容（保留表头）
    ui->tableWidget->setRowCount(0);  // 重置行数为0，避免残留空行

    int row = 0;
    while (query.next()) {
        ui->tableWidget->insertRow(row); // 插入新行
        // 书号（第0列）
        QTableWidgetItem* idItem = new QTableWidgetItem(query.value("bookid").toString());
        idItem->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); // 居中
        ui->tableWidget->setItem(row, 0, idItem);

        // 书名（第1列）
        QTableWidgetItem* nameItem = new QTableWidgetItem(query.value("name").toString());
        nameItem->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); // 居中
        ui->tableWidget->setItem(row, 1, nameItem);

        // 数量（第2列）
        QTableWidgetItem* numItem = new QTableWidgetItem(query.value("num").toString());
        numItem->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); // 居中
        ui->tableWidget->setItem(row, 2, numItem);
        row++;
    }
}


void MainWindow::on_lineEdit_returnPressed()
{

}

void MainWindow::on_lineEdit_selectionChanged()
{
    ui->widget->show();
}
